<template>
  <div style="display: flex;justify-content: space-between;height: calc(100vh - 350px )" v-loading="loading">
    <div class="left">
      <el-page-header @back="goBack"></el-page-header>
      <div class="top" v-if="cameraList.length==0">暂无摄像头列表</div>
      <div class="top" v-if="cameraList.length!=0">
        <p class="cctvList" v-for="(item, index) in cameraList"
           :key="item.id"
           @click="handleClick(item,index)">
        <span id="s1" ref="s1" :style="{
        backgroundColor: activeIndex === index ? '#303e9d' : '#999'
      }"></span>
          <span>{{ item.serialNumber }}</span>
          <span>
          <img v-if="activeIndex == index" src="@/assets/img/play.svg">
          <img v-else src="@/assets/img/noPlay.svg">
        </span>
        </p>
      </div>
      <div style="margin-top: 20px">
        <div ref="videoContainer">
          <!-- Video element will be injected here -->
        </div>
      </div>
    </div>
    <div class="right">
      <el-select v-model="templateId" style="width: 100%" placeholder="请选择模板" size="small" @change="changeTemplate">
        <el-option v-for="item in templateList" :value="item.templateId" :label="item.templateName"
                   :key="item.templateId"></el-option>
      </el-select>
      <el-input size="small" placeholder="请输入问题名称" style="margin-top: 10px"></el-input>
      <div class="pics">
        <p :class="{ active: activeNum === 0 }" @click="activeNum = 0">
          <span><a>{{ completeCount }}</a>/<a>{{ totalCount }}</a></span>
          <span style="color: #919398;font-size: 12px;font-weight: 400">全部</span></p>
        <p :class="{ active: activeNum === 1 }" @click="activeNum = 1">
          {{ totalCount - completeCount }}
          <span style="color: #919398;font-size: 12px;font-weight: 400">未考评</span>
        </p>
        <p :class="{ active: activeNum === 2 }" @click="activeNum = 2" style="color: #13ce66">
          {{ hegeCount }}
          <span style="color: #919398;font-size: 12px;font-weight: 400">合格</span>
        </p>
        <p :class="{ active: activeNum === 3 }" @click="activeNum = 3" style="color: #ce0e0f">
          {{ buhegeCount }}
          <span style="color: #919398;font-size: 12px;font-weight: 400">不合格</span>
        </p>
      </div>
      <div style="margin-top: 10px;">
        <el-tabs
            v-model="activeTab"
            type="card"
            class="custom-tabs"
            @tab-click="handleTabClick"
        >
          <el-tab-pane
              v-for="item in menuList"
              :key="item.largeId"
              :label="item.largeName"
              :name="item.largeName"
          >
            <el-collapse>
              <el-collapse-item v-for="a in item.termVoList">
                <template slot="title">
                  <div style="display: flex">
                    <p>{{ a.termName }}</p>
                    <p style="margin-left: 50px;color: #13ce66">{{ a.count }}/{{ a.list.length }}</p>
                  </div>
                </template>
                <div>
                  <div v-for="(b,index) in a.list" class="collapseList">
                    <span style="font-weight: bold">[{{ b.problemScore }}分] {{ b.problemName }}</span>
                    <p style="margin: 8px 0">
                      <el-button icon="el-icon-camera" @click="takePhoto(b)"></el-button>
                      <el-button icon="el-icon-edit-outline" @click="b.show=true"></el-button>
                    </p>
                    <p v-if="b.imgUrl">
                      <span v-for="c in b.imgUrl"><el-image style="width: 80px" :src="c" :preview-src-list="[c]"/><i
                          class="el-icon-delete"
                          @click="deletePic(b,c)"></i></span>
                    </p>
                    <p v-if="b.hege==2" style="margin-top: 10px">扣:{{ b.problemScore }}分</p>
                    <p v-else style="margin-top: 10px">扣:0分</p>
                    <p style="margin-top: 10px">
                      <el-button
                          :type="b.hege === 1 ? 'success' : 'default'"
                          @click="setHegeAndCount(a, b, 1)"
                          size="small"
                      >
                        合格
                      </el-button>
                      <el-button
                          :type="b.hege === 2 ? 'danger' : 'default'"
                          @click="setHegeAndCount(a, b, 2)"
                          size="small"
                      >
                        不合格
                      </el-button>
                    </p>
                    <p style="margin-top: 10px">
                      <el-input size="small" placeholder="请输入备注" v-if="b.show" v-model="b.remark"></el-input>
                    </p>
                  </div>
                </div>

              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="submitBtn">
      <p><span style="display:block;font-size: 15px;color: #ce0e0f">计算得分: {{ info.computeScore }}</span>
        <span style="display:block;">总分:{{ info.totalScore }}</span></p>
      <p>
        <el-button style="background-color:#303e9d;color: #eeeeee" @click="_submit" size="small">提 交</el-button>
      </p>
    </div>
  </div>
</template>

<script>
import Videojs from 'video.js'
import 'video.js/dist/video-js.css'

export default {
  name: "startAssessment",
  data() {
    return {
      activeIndex: 0,
      activeNum: 0,
      loading: false,
      completeCount: 0,
      totalCount: 0,
      unPatorl: 0,
      hegeCount: 0,
      buhegeCount: 0,
      show: false,
      activeTab: '',
      templateId: "",
      assignTaskId: "",
      templateList: [],
      cameraList: [],
      menuList: [],
      myPlayer: null,
      count: 0,
      info: {},
      infoBar: [],
      serialNumber: "",
    }
  },
  computed: {
    computedScore() {
      let deducted = 0;
      this.menuList.termVoList.forEach(term => {
        term.list.forEach(problem => {
          if (problem.hege === 2) {
            deducted += Number(problem.problemScore || 0);
          }
        });
      });
      return this.info.computeScore - deducted;
    }
  },
  watch: {
    '$route.query': {
      handler(newQuery) {
        if (this.$route.path === '/startAssessment') {
          this.fetchUser(newQuery)
        }else{
          this.close()
        }
      },
      immediate: true
    }
  },
  methods: {
    setHegeAndCount(a, b, val) {
      const prevHege = b.hege;
      this.hegeCount = this.hegeCount || 0;
      this.buhegeCount = this.buhegeCount || 0;

      // 处理切换分数逻辑
      b.hege = val;
      if (b._counted === undefined) {
        b._counted = false;
      }
      if (prevHege !== val) {
        if (val === 2) {
          // 切换成不合格 -> 扣分
          this.info.computeScore -= Number(b.problemScore || 0);
        } else if (val === 1 && prevHege === 2) {
          // 不合格 -> 合格，加回分
          this.info.computeScore += Number(b.problemScore || 0);
        }
        this.info.computeScore = Math.min(
            this.info.totalScore,
            Math.max(0, this.info.computeScore)
        );

        // 处理 hegeCount 和 buhegeCount 的变更
        if (prevHege === 1 && val === 2) {
          // 合格 -> 不合格
          this.hegeCount = Math.max(0, this.hegeCount - 1);
          this.buhegeCount += 1;
        } else if (prevHege === 2 && val === 1) {
          // 不合格 -> 合格
          this.buhegeCount = Math.max(0, this.buhegeCount - 1);
          this.hegeCount += 1;
        }
      }

      // === 2. 初次统计 count ===
      if (b.imgUrl && b.imgUrl.length > 0 && b.hege && !b._counted) {
        a.count += 1;
        this.completeCount += 1;
        b._counted = true;

        // 初次设置时也需要根据 hege 判断是合格还是不合格
        if (val === 1) {
          this.hegeCount += 1;
        } else if (val === 2) {
          this.buhegeCount += 1;
        }
      }
    },
    deletePic(item, url) {
      const index = item.imgUrl.indexOf(url);
      if (index !== -1) {
        item.imgUrl.splice(index, 1);
      }
    },
    takePhoto(val) {
      this.$api.patrolGetCameraCapture({serialNumber: this.serialNumber}).then(res => {
        val.imgUrl.push('https:' + res)
      })

    },
    handleTabClick(tab) {
    },
    async fetchUser(val) {
      this.assignTaskId = val.assignTaskId
      this.getTemplateData();
      if (!val?.assignTaskId) return;
      try {
        const res = await this.$api.patrolGetStoreAllCamera({assignTaskId: val.assignTaskId,type:1});
        if (Array.isArray(res)) {
          this.cameraList = res;
          // 可选：找到第一个带有 videoUrl 的摄像头对象
          const target = res.find(item => item.videoUrl);
          if (target) {
            this.serialNumber = target.serialNumber
            this.init(target.videoUrl, target.serialNumber);
          } else {
            console.warn('未找到有效的摄像头视频 URL');
          }
        } else {
          console.warn('接口返回格式异常');
        }
      } catch (err) {
        console.error('获取摄像头列表失败:', err);
      }
    },
    getTemplateData() {
      this.loading = true
      const data = {
        pageNumber: 1,
        pageSize: 10000,
        state: 1
      }
      this.$api.patrolGetPatrolTemplateVo(data).then(res => {
        this.templateList = res.data
        if (this.templateList.length > 0) {
          this.templateId = this.templateList[0].templateId;
        }
        this.getLargeInfo(this.templateId)
        this.loading = false
      })
    },
    getLargeInfo(id) {
      this.$api.patrolGetPatrolTemplateConfig({templateId: id}).then(res => {
        this.info = res
        this.$set(this.info, 'computeScore', res.totalScore);
        this.menuList = res.largeVoList
        this.menuList.forEach(a => {
          a.termVoList?.forEach(b => {
            this.$set(b, 'count', 0);
            this.totalCount += b.list?.length || 0;
            b.list?.forEach(c => {
              this.$set(c, 'show', false);
              this.$set(c, 'imgUrl', []);
              this.$set(c, 'hege', "");
            });
          });
        });
        if (this.menuList.length > 0) {
          this.activeTab = this.menuList[0].largeName;
        }
      })
    },
    changeTemplate(val) {
      this.getLargeInfo(val)
    },
    handleClick(item, index) {
      this.activeIndex = this.activeIndex === index ? null : index;
      this.init(item.videoUrl, item.serialNumber)
    },
    init(url, row) {
      this.close()
      this.$nextTick(() => {
        this.createVideoElement()
        this.setUrl(url)
      })
      this.serialNumber = row
    },
    createVideoElement() {
      const videoContainer = this.$refs.videoContainer
      videoContainer.innerHTML = ''
      const videoElement = document.createElement('video')
      videoElement.id = 'videoPlayer'
      videoElement.className = 'video-js'
      videoElement.muted = true
      videoContainer.appendChild(videoElement)
    },
    setUrl(nowPlayVideoUrl) {
      const options = {
        autoplay: true,
        controls: true,
        width: "800px",
        height: "500px",
        notSupportedMessage: "网络不稳定，请稍后再试~",
        sources: [
          {
            src: nowPlayVideoUrl,
            type: 'application/x-mpegURL',
            cors: true,
          },
        ],
      }

      this.myPlayer = Videojs('videoPlayer', options)
    },
    close() {
      if (this.myPlayer) {
        this.myPlayer.dispose()
        this.myPlayer = null
      }
    },
    beforeDestroy() {
      if (this.myPlayer) {
        this.myPlayer.dispose()
        this.myPlayer = null
      }
    },
    goBack() {
      this.$router.back()
      this.close()
    },
    _submit() {
      const submitList = [];
      this.info.largeVoList.forEach(large => {
        large.termVoList.forEach(term => {
          term.list.forEach(problem => {
            submitList.push({
              largeId: large.largeId,
              termId: term.termId,
              problemId: problem.problemId,
              problemRemark: problem.remark || "",
              problemImg: problem.imgUrl.toString(),
              isQualified: problem.hege,
              recordScore: problem.problemScore
            });
          });
        });
      });
      let resultList = {
        list: submitList,
        patrolTemplateId: this.info.templateId,
        assignTaskId: this.assignTaskId,
        fullScore: this.info.totalScore,
        patrolScore: this.info.computeScore,
        patrolType: 1
      }

      this.$api.patrolAddPatrolRecord(resultList).then(res => {
        if (res == 1) {
          this.$message.success('添加考评成功！')
          this.$router.back()
        }
      })
    },
  }
}
</script>

<style scoped lang="less">
.pics {
  width: 100%;
  height: 60px;
  margin-top: 10px;
  background-color: #eee;
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  justify-content: space-between;
  align-items: center;

  p {
    padding: 5px 15px;
    width: 20%;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    font-weight: bold;
  }

  p.active {
    background-color: #fff;
  }

  span {
    display: block;
  }
}

.top {
  display: flex;
  margin-top: 20px;
}

.left {
  width: 70%;
  padding: 10px;
  box-sizing: border-box;
}

.collapseList {
  width: 100%;
  border: 1px solid #eee;
  margin-bottom: 10px;
  padding: 10px;
  box-sizing: border-box;
}

.right {
  width: 28%;
  border-left: 1px solid #eee;
  padding-left: 20px;
  height: calc(100vh - 180px);
  overflow: scroll;
}

.submitBtn {
  display: flex;
  height: 50px;
  align-items: center;
  background-color: #eee;
  padding: 10px 10px;
  justify-content: space-between;
  position: absolute;
  bottom: 20px;
  right: 8px;
  width: 28%
}

.cctvList {
  width: 150px;
  height: 50px;
  margin-right: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 10px;
  box-sizing: border-box;
  justify-content: space-between;
  background-color: #eee;
  align-items: center;

  img {
    width: 30px;
    height: 30px;
    margin-top: 5px;
  }

  #s1 {
    width: 10px;
    height: 10px;
    display: block;
    background-color: #303e9d;
    border-radius: 50%;
  }
}

.custom-tabs {
  --el-tabs-header-height: 40px;
}

.custom-tabs ::v-deep(.el-tabs__nav-wrap) {
  overflow-x: auto !important;
}

.custom-tabs ::v-deep(.el-tabs__nav) {
  display: inline-flex;
  white-space: nowrap;
}

.custom-tabs ::v-deep(.el-tabs__item) {
  padding: 0 20px;
  font-size: 14px;
  color: #333;
  transition: 0.2s;
}

.custom-tabs ::v-deep(.el-tabs__item.is-active) {
  color: #303e9d;
  border-bottom: 2px solid #303e9d;
}
</style>